# -*- coding:UTF-8 -*-
import requests
import csv
import random
import time
import socket
import http.client
import hashlib
import os
# import urllib.request
from bs4 import BeautifulSoup

# 请求url获取内容


def get_content(url, data=None):
    header = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
    }
    timeout = random.choice(range(80, 180))
    while True:
        try:
            rep = requests.get(url, headers=header, timeout=timeout)
            rep.encoding = 'utf-8'
            # req = urllib.request.Request(url, data, header)
            # response = urllib.request.urlopen(req, timeout=timeout)
            # html1 = response.read().decode('UTF-8', errors='ignore')
            # response.close()
            break
        # except urllib.request.HTTPError as e:
        #         print( '1:', e)
        #         time.sleep(random.choice(range(5, 10)))
        #
        # except urllib.request.URLError as e:
        #     print( '2:', e)
        #     time.sleep(random.choice(range(5, 10)))
        except socket.timeout as e:
            print('3:', e)
            time.sleep(random.choice(range(8, 15)))

        except socket.error as e:
            print('4:', e)
            time.sleep(random.choice(range(20, 60)))

        except http.client.BadStatusLine as e:
            print('5:', e)
            time.sleep(random.choice(range(30, 80)))

        except http.client.IncompleteRead as e:
            print('6:', e)
            time.sleep(random.choice(range(5, 15)))

    return rep.text
    # return html_text

# 解析html获取数据


def get_data(html_text):
    final = []
    bs = BeautifulSoup(html_text, "html.parser")  # 创建BeautifulSoup对象
    body = bs.body  # 获取body部分
    ul = body.find('ul', {'class': 'exh_content_list'})  # 获取ul部分
    li = ul.find_all('li')  # 获取所有的li

    for item in li:  # 对每个li标签中的内容进行遍历
        temp = []
        # 找class为name的p标签
        name = item.find('p', {'class': 'name'}).string
        # 找img的src
        img = item.find('a', {'class': 'img'}).find('img')['src']
        download_img(img)
        # 找p标签下的a标签中的文本
        company = item.find('p', {'class', 'company'}).find('a').string
        temp.append(name)
        temp.append(img)
        temp.append(company)
        final.append(temp)  # 将temp加到final中

    return final

# 下载图片


def download_img(url):
    image = requests.get(url)
    if image.status_code == 200:
        filename = os.path.basename(url)
        filepath = r'F:/technology-sharing/1.网络爬虫实践/alighting/image/%s' % filename
        with open(filepath, 'wb') as f:
            f.write(image.content)
    del image

# 写入文件


def write_data(data, name):
    file_name = name
    with open(file_name, 'a', errors='ignore', newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerows(data)


if __name__ == '__main__':
    url = 'https://www.alighting.com/views/SearchGoods.aspx?cid=308&page=1'
    html = get_content(url)
    result = get_data(html)
    write_data(result, 'product.csv')
